import React, { useEffect, useState } from 'react';
import { Button, Table, Tag, notification, Col, Drawer, Form, Input, Row, Select, Tree } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import _ from 'lodash'

import { useNavigate } from 'react-router-dom';
import service from '../../../api'

function Account(props) {
    //表单setFieldValue功能
    const [form] = Form.useForm()
    //下拉菜单
    const { Option } = Select;
    //抽屉的显示属性
    const [open, setOpen] = useState(false);
    const [accountlist, setAccountlist] = useState([])
    //分页
    const [pagination, setPagination] = useState({ current: 0, pageSize: 0 });
    //树状控件
    const [checkedKeys, setCheckedKeys] = useState([]);
    const [defaultExpandAll, setdefaultExpandAll] = useState(true);
    //保存管理员id，用于识别新增和编辑
    const [adminId,setAdminId] = useState('')
    //请求管理员列表
    var getAccountlist = async () => {
        var res = await service.admin.admin_list();
        setAccountlist(res.data.data)
    }

    useEffect(() => {
        getAccountlist()
    }, [])

    //抽屉
    const showDrawer = () => {
        setOpen(true);
    };
    const onClose = () => {
        setOpen(false);
        setAdminId('')
        form.setFieldsValue({adminname:'',password:'',role:null,checkedKeys:[]})
        setCheckedKeys([])
    };

    //验证手机号
    var adminnameValidator = (rule, value, callback) => {
        if (value.length<7) {
            callback()
        } else {
            callback(new Error('账号格式错误，请重新输入!'))
        }
    }
    //验证密码
    var passwordValidator = (rule, value, callback) => {
        // if (/^\d{6}$/.test(value)) {
        if (value!='') {
            callback()
        } else {
            callback(new Error('密码格式错误，请重新输入'))
        }
    }
    //树状组件
    const onCheck = (checkedKeysValue) => {
       
        setCheckedKeys(checkedKeysValue);
        form.setFieldValue('checkedKeys', checkedKeysValue)
    };
    const treeData = [
        {
            key: '1',
            title: '轮播图管理',
            children: [{
                key: '1-1',
                title: '轮播图列表',
            },]
        },
        {
            key: '2',
            title: '账号管理',
            children: [{
                key: '2-1',
                title: '管理员列表',
            },]
        },
        {
            key: '3',
            title: '产品管理',
            children: [
                {
                    key: '3-1',
                    title: '产品列表',
                },
                {
                    key: '3-2',
                    title: '秒杀列表',
                },
                {
                    key: '3-3',
                    title: '推荐列表',
                },
                {
                    key: '3-4',
                    title: '筛选列表',
                },
            ]
        },
        {
            key: '4',
            title: '数据可视化',
            children: [{
                key: '4-1',
                title: 'echarts使用',
            },]
        },
        {
            key: '5',
            title: '编辑器',
            children: [{
                key: '5-1',
                title: '富文本编辑器',
            },]
        },
        {
            key: '6',
            title: 'excel管理',
            children: [
                {
                    key: '6-1',
                    title: 'excel导入',
                },
                {
                    key: '6-2',
                    title: 'excel导出',
                },
            ]
        },
        {
            key: '7',
            title: '地图管理',
            children: [{
                key: '7-1',
                title: '百度地图',
            },]
        },
    ];
    //表单验证通过时执行
    const onFinish = async (values) => {
        if (adminId) {   
            //编辑请求
            var addres=await service.admin.admin_update(values)
            notification.destroy();
            if (addres.data.code == 200) {
                //弹出通知框
                notification.success({ message: '修改成功!' });
                setAdminId('')
            } else {
                notification.error({ message: '修改失败!' });
                setAdminId('')
            }
        }else{
            //发出新增请求
            var res = await service.admin.admin_add(values)
            notification.destroy();
            if (res.data.code == 200) {
                //弹出通知框
                notification.success({ message: '新增成功!' });
            } else {
                notification.error({ message: '新增失败!' });
            }
        }

    };

  //页码   一直显示NaN:pageSize没有驼峰命名
    var onPageChange = (pagination) => {

        setPagination(pagination)
    }  
    //进入编辑管理员界面
    var toEdit = async (adminInfo) => {
        setOpen(true)
        form.setFieldsValue(adminInfo)//数据回显
        setCheckedKeys(adminInfo.checkedKeys)
        //保存管理员id
        setAdminId(adminInfo.adminid)
    }
    //删除管理员
    var toDelete = async (adminid) => {

        var res = await service.admin.admin_delete({ adminid });
        if (res.data.code == 200) {
            notification.success({ message: '删除成功!' });
            //删除本地图片
            var index = accountlist.findIndex((item) => item.adminid == adminid)
            if (index != -1) {
                //对本地数据深拷贝( 否则组件不更新 )；实现删除后列表立即更新的功能
                var newaccountlist = _.cloneDeep(accountlist);
                newaccountlist.splice(index, 1);
                setAccountlist(newaccountlist);
            }
        }
    }

    const columns = [
        {
            title: '序号',
            key: 'number',
            //_起到占位作用，此处需要一个参数，但是我们用不上
            render: (_, record, index) => <div>{(pagination.current - 1) * pagination.pageSize + index + 1}</div>,
        },
        {
            title: '账号',
            key: 'adminname',
            width: 200,
            dataIndex: 'adminname',
        },
        {
            title: '权限',
            key: 'right',
            //   render: (_,record,index) => <a href={record.address}> 链接 </a>,
            render: (_, record, index) => <Tag color="#87d068">{record.role == '1' ? '管理员' : '超级管理员'}</Tag>,
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record, index) => <div><Button default onClick={() => { toEdit(record) }}> Edit </Button>&nbsp;<Button danger type="primary" onClick={() => { toDelete(record.adminid) }}> Delete </Button></div>,
        },
    ]
    return (
        <div className='account-box'>
            <div className="account-box-header">
                <Button type="primary" onClick={showDrawer}>添加管理员 <PlusOutlined /></Button>
            </div>
            <Table className='table' onChange={onPageChange} style={{ marginTop: 20 }} columns={columns} dataSource={accountlist} />

            {/* 抽屉 */}
            <Drawer title={adminId?"编辑管理员":"添加管理员"} width={400} onClose={onClose} open={open} bodyStyle={{ paddingBottom: 80, }}>
                <Form layout="vertical" onFinish={onFinish} form={form}>
                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item name="adminname" label="账号"
                                rules={[{ validator: adminnameValidator }]}>
                                    {/* adminId不为空，说明是新增，disabled值为true,输入框禁用 */}
                                <Input placeholder="请输入账号" disabled={adminId!=''}/>
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item name="password" label="密码"
                                rules={[{ validator: passwordValidator }]}>
                                <Input placeholder="请输入密码" disabled={adminId!=''}/>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={14}>
                            <Form.Item
                                name="role"
                                label="角色"
                                rules={[
                                    {
                                        required: true,
                                        message: '角色不能为空',
                                    },
                                ]}>
                                <Select placeholder="请选择角色"
                                    options={[
                                        { value:1, label: '管理员' },
                                        { value:2, label: '超级管理员' }
                                    ]}>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item name="checkedKeys" label="权限">
                                <Tree
                                    checkable
                                    defaultExpandAll={defaultExpandAll}
                                    onCheck={onCheck}
                                    checkedKeys={checkedKeys}
                                    treeData={treeData}
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Button type="primary" size='large' htmlType="submit" style={{ width: 200 }}>
                       {adminId?"编辑管理员":"添加管理员"}
                    </Button>
                </Form>
            </Drawer>
        </div>
    );
}

export default Account;